package com.ai.smlcore.control;

import java.lang.reflect.Method;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.ai.common.xml.util.ControlConstants.RETURN_CODE;
import com.ai.frame.IControlService;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.frame.util.JsonUtil;
import com.ai.smlcore.util.StringUtil;
import com.ai.smlcore.util.ThreadLocalParam;

/**
 */
public class ControlServiceImpl implements IControlService, BeanFactoryAware {
	private static final Logger logger = LoggerFactory.getApplicationLog(ControlServiceImpl.class);

	private BeanFactory factory;

	public void setBeanFactory(BeanFactory factory) {
		this.factory = factory;
	}

	public String execute(String json) {
		InputObject inObj = null;
		OutputObject outObj = new OutputObject();
		long start = System.currentTimeMillis();
		try {
			inObj = JsonUtil.json2InputObject(json);

			outObj.setReturnCode(RETURN_CODE.IS_OK);
			if (inObj != null) {
				ThreadLocalParam.getThreadInstance().setLogParam(inObj.getLogParams());
				String logParam = "OP_REQST_NO=" + inObj.getLogParams().get("OP_REQST_NO") + ",service="
						+ inObj.getService() + ", method=" + inObj.getMethod();
				logger.info("INVOKE START!", logParam);
				if (StringUtil.isEmpty(inObj.getService()) || StringUtil.isEmpty(inObj.getMethod())) {
					throw new Exception("服务名或方法不能为空!");
				}
				
				Object object = factory.getBean(inObj.getService());
				Method mth = object.getClass().getMethod(inObj.getMethod(), InputObject.class, OutputObject.class);
				mth.invoke(object, inObj, outObj);
				logger.info("INVOKE SECCESS!", logParam + ", COST=" + (System.currentTimeMillis() - start) + "ms");
			} else {
				throw new Exception("InputObject can't be null !!!");
			}
		} catch (Exception e) {
			if (inObj != null && inObj.getLogParams() != null
					&& StringUtil.isNotEmpty(inObj.getLogParams().get("OP_REQST_NO"))) {
				logger.error("execute INVOKE ERROR! ",
						"OP_REQST_NO = " + inObj.getLogParams().get("OP_REQST_NO") + ",  JSON = " + json, e);
			} else {
				logger.error("execute INVOKE ERROR! ", "JSON = " + json, e);
			}
			// 异常处理
			outObj.setReturnCode(RETURN_CODE.SYSTEM_ERROR);
			outObj.setReturnMessage(e.getMessage() == null ? e.getCause().getMessage() : e.getMessage());
		} finally {
			// saveUserOperLog(start, System.currentTimeMillis(), inObj,
			// outObj);
		}
		return JsonUtil.outputObject2Json(outObj);
	}
}
